import { _decorator, Component, Node, math, randomRange, Prefab, instantiate, v3, randomRangeInt, view, UITransform } from 'cc';
import { EnemyConstant } from './constant/EnemyConstant';
import { SysContant } from './constant/SysContant';
import {Enemy} from './Enemy';
const { ccclass, property } = _decorator;


/**
 * 
 * 每秒生成 a 敌人  ==> a 随着游戏时长而增多, 达到巅峰后不再增多
 * a个敌人中有 enemy1 2 3
 * 每个enemy x
 * 
 * 
 * 
 */
@ccclass('EnemyFactory')
export class EnemyFactory extends Component {
    
    @property(Prefab)
    enemyPrefabs: Prefab[] = []
    viewSize: math.Size;
    
    
    start() {
        this.viewSize = view.getVisibleSize()
    }

    update(deltaTime: number) {
        
    }

    /**
     * 开始生成敌人
     */
    attact() {
        this.schedule(this.generateByTime, 1)
    }
    
    unattact() {
        this.unschedule(this.generateByTime)
    }
    /**
     * 清理所有敌人
     */
    clearAll() {
        this.node.removeAllChildren()
    }

    /**
     * 消灭所有敌人
     */
    killAllEnemys() {
        // 遍历所有的敌人, 调用杀死他的方法
        let enemys = this.node.children
        for (const enemy of enemys) {
            let {x, y} = enemy.position
            let maxY = this.viewSize.height / 2 + enemy.getComponent(UITransform).height / 2
            console.log('maxY', maxY);
            
            if(y > maxY || y < -maxY) {
                break
            }

            enemy.getComponent(Enemy).killed(4)
        }

    }


    generateByTime() {
        // 此刻每秒生成敌人
        let n = Math.ceil(EnemyConstant.maxPer * SysContant.inst.bestRate())
        
        for (let i = 0; i < n; i++) {
            this.generateOneEnemy()
        }
    }

    // 生成一个敌人
    generateOneEnemy() {
        // a个敌人中有 enemy1 2 3  6 3 1

        let r = randomRange(0, 10)

        if (r < 7.5) {
            this.generateEnemy(0)
        } else if(r >=7.5 && r < 9.5) {
            this.generateEnemy(1)
        }else {
            this.generateEnemy(2)
        }
    }

    
    generateEnemy(index: number) {
        let enemy = instantiate(this.enemyPrefabs[index])

        let maxX = this.viewSize.width / 2 - enemy.getComponent(UITransform).width / 2

        enemy.setPosition(v3(
            randomRange(-maxX, maxX),
            500 + randomRangeInt(0, 50)
        ))

        enemy.setParent(this.node)

    }

}


